package com.ftf.tp.blog.application.eventHandler;

import com.alibaba.fastjson.JSONObject;
import com.ftf.tp.blog.application.adapter.producer.NeedSaveEventResult;
import com.ftf.tp.blog.application.service.command.ConfigureCommandService;
import com.ftf.tp.blog.domain.article.aggregate.ArticleAgg;
import com.ftf.tp.blog.domain.article.event.PublishArticleEvent;
import com.ftf.tp.blog.domain.article.repository.ArticleRepository;
import com.ftf.tp.common.core.constants.ResultEnum;
import com.ftf.tp.common.core.utils.ResultVO;
import com.ftf.tp.common.core.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @author tanghao
 * @date 2022/8/5
 */
@Slf4j
@Component
public class ArticleEventHandler {

    @Resource
    private ConfigureCommandService configureApplicationService;

    @Resource
    private ArticleRepository articleRepository;

    @NeedSaveEventResult
    @TransactionalEventListener
    public ResultVO<?> handleEvent(PublishArticleEvent event) {
        try {
            log.info("接受到文章发布事件 id={} {}", event.getId(), JSONObject.toJSONString(event));
            //调用配置应用服务,同步配置信息
            ArticleAgg articleAgg = event.getData();
            configureApplicationService.articleConfigureSync(articleAgg);
            //同步ES数据
            articleRepository.syncEsArticle(articleAgg);
            //缓存配置信息
            articleRepository.getArticleConfigureById(articleAgg.getId());
            return ResultVOUtil.success();
        } catch (Exception e) {
            log.error("文章发布事件消费失败",e);
            return ResultVOUtil.error(ResultEnum.INNER_ERROR.getCode(), e.getMessage());
        }
    }

}
